package com.xinjiang.electricpower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.ruoyi.common.core.utils.StringUtils;
import com.xinjiang.electricpower.domain.DTO.WorkOrderEarlyWarningDTO;
import com.xinjiang.electricpower.domain.DTO.WorkOrderMonitorDTO;
import com.xinjiang.electricpower.domain.DTO.WorkOrderPoolDTO;
import com.xinjiang.electricpower.domain.XjOrderGeneral;
import com.xinjiang.electricpower.domain.vo.*;
import com.xinjiang.electricpower.enums.ElectricPowerEnums;
import com.xinjiang.electricpower.mapper.WorkOrderPoolMapper;
import com.xinjiang.electricpower.mapper.XjOrderGeneralMapper;
import com.xinjiang.electricpower.mapper.XjOrderSourceMapper;
import com.xinjiang.electricpower.service.IUserAuthService;
import com.xinjiang.electricpower.service.IWorkOrderMonitorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author feizhao
 * @date 2022/11/21
 * @apiNote
 */
@Slf4j
@Service
public class WorkOrderMonitorServiceImpl extends ServiceImpl<XjOrderGeneralMapper, XjOrderGeneral> implements IWorkOrderMonitorService {


    @Autowired
    private IUserAuthService iUserAuthService;
    @Autowired
    private WorkOrderPoolMapper workOrderPoolMapper;

    /**
     * 统计当月的各个状态的工单数
     */
    @Override
    public List<WorkOrderStatisticsStatusVO> getNumsByStatus() {
        QueryWrapper<XjOrderGeneral> queryWrapper = new QueryWrapper<>();
        AuthInfoVo authStr = iUserAuthService.getAuthStr();
        queryWrapper.eq("month(xog.dispatch_time)", LocalDate.now().getMonth().getValue());
        queryWrapper.eq( StringUtils.isNotEmpty(authStr.getOrgNo()),"xog.org_no",authStr.getOrgNo());
        queryWrapper.in( ObjectUtils.isNotEmpty(authStr.getConsNo()),"xog.cons_no",authStr.getConsNo());
        queryWrapper.groupBy("status");
        return baseMapper.countWorkOrdersByStatus(queryWrapper);
    }

    /**
     * 统计指定年月的各个状态的工单数
     *
     * @param workOrderPoolDTO 筛选时间
     */
    @Override
    public List<WorkOrderStatisticsStatusVO> getNumsByStatus(WorkOrderPoolDTO workOrderPoolDTO) {
        QueryWrapper<XjOrderGeneral> queryWrapper = new QueryWrapper<>();
        AuthInfoVo authStr = iUserAuthService.getAuthStr();
        //DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM");
        //queryWrapper.eq("DATE_FORMAT(dispatch_time, '%Y-%m') ", workOrderPoolDTO.getTimeGranularityMonth().format(dateTimeFormatter));
        queryWrapper.eq(StringUtils.hasText(workOrderPoolDTO.getSystemId()),"xos.id",workOrderPoolDTO.getSystemId());
        queryWrapper.eq(StringUtils.hasText(workOrderPoolDTO.getType()),"xog.type",workOrderPoolDTO.getType());
        queryWrapper.eq(StringUtils.isNotEmpty(authStr.getOrgNo()),"xog.org_no",authStr.getOrgNo());
        queryWrapper.in(ObjectUtils.isNotEmpty(authStr.getConsNo()),"xog.cons_no",authStr.getConsNo());
        queryWrapper.ge(ObjectUtils.isNotEmpty(workOrderPoolDTO.getBeginDateStart()), "CONVERT(xog.begin_date,date)", workOrderPoolDTO.getBeginDateStart());
        queryWrapper.le(ObjectUtils.isNotEmpty(workOrderPoolDTO.getBeginDateEnd()), "CONVERT(xog.begin_date,date)", workOrderPoolDTO.getBeginDateEnd());
        queryWrapper.groupBy("status");
        return baseMapper.countWorkOrdersByStatus(queryWrapper);
    }

    /**|
     * 统计工单池-工单占比状态
     * @param workOrderPoolDTO
     * @return
     */
    @Override
    public List<WorkOrderStatisticsStatusVO> getNumsByStatusTest(WorkOrderPoolDTO workOrderPoolDTO) {
        AuthInfoVo authStr = iUserAuthService.getAuthStr();
        return workOrderPoolMapper.getOrderPoolStatusCount(workOrderPoolDTO, authStr);
    }

    /**
     * 统计当月的各个系统的待办的工单数
     */
    @Override
    public List<SystemWorkOrderStatisticsStatusVO> getNumsBySystemWorkOrderStatus() {
        AuthInfoVo authStr = iUserAuthService.getAuthStr();
        QueryWrapper<SystemWorkOrderStatisticsStatusVO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("xog.status",1);
        queryWrapper.eq(StringUtils.isNotEmpty(authStr.getOrgNo()),"xog.org_no",authStr.getOrgNo());
//        queryWrapper.eq("xog.org_no",654010711);
        queryWrapper.in(ObjectUtils.isNotEmpty(authStr.getConsNo()),"xog.cons_no",authStr.getConsNo());
        queryWrapper.groupBy("xos.id");
        List<SystemWorkOrderStatisticsStatusVO> vos = new ArrayList<>();
        List<SystemWorkOrderStatisticsStatusVO> systemWorkProcessOrders = baseMapper.countSystemWorkProcessOrders(queryWrapper);
        //查询所有系统来源，默认工单数量为0
        List<SystemOrdersVO> systemOrdersVOS = xjOrderSourceMapper.selectSourceName();
        for (SystemOrdersVO systemOrdersVO : systemOrdersVOS) {
            SystemWorkOrderStatisticsStatusVO vo = new SystemWorkOrderStatisticsStatusVO();
            vo.setSourceId(systemOrdersVO.getId());
            vo.setSystemName(systemOrdersVO.getSystemName());
            vo.setOrderNum("0");
            if (CollectionUtils.isNotEmpty(systemWorkProcessOrders) && systemWorkProcessOrders.size() > 0) {
                for (SystemWorkOrderStatisticsStatusVO systemWorkProcessOrder : systemWorkProcessOrders) {
                    if (systemWorkProcessOrder.getSourceId().equals(systemOrdersVO.getId())) { ;
                        vo.setOrderNum(systemWorkProcessOrder.getOrderNum().toString());
                    }
                }
            }
            vos.add(vo);
        }
        return vos;
    }
    /**
     * 查询工单监控列表
     *
     * @param page                分页对象
     * @param workOrderMonitorDTO 工单DTO类
     * @return PageInfo<WorkOrderMonitorVO> 返回分页的工单预警信息
     */
    @Override
    public PageInfo<WorkOrderMonitorVO> selectWorkOrderMonitorPage(PageDTO<WorkOrderMonitorVO> page, WorkOrderMonitorDTO workOrderMonitorDTO) {
        QueryWrapper<WorkOrderMonitorVO> wrapper = new QueryWrapper<>();
        //工单编号用原系统的工单编号查询
        wrapper.like(StringUtils.hasText(workOrderMonitorDTO.getGeneralOrderNo()),"xog.order_no",workOrderMonitorDTO.getGeneralOrderNo());
        wrapper.eq(StringUtils.hasText(workOrderMonitorDTO.getSourceId()),"xos.id",workOrderMonitorDTO.getSourceId());
        wrapper.eq(StringUtils.hasText(workOrderMonitorDTO.getType()),"xog.type",workOrderMonitorDTO.getType());
        wrapper.eq(StringUtils.hasText(workOrderMonitorDTO.getStatus()),"xog.status",workOrderMonitorDTO.getStatus());
        AuthInfoVo authStr = iUserAuthService.getAuthStr();
        wrapper.eq(StringUtils.isNotEmpty(authStr.getOrgNo()),"xog.org_no",authStr.getOrgNo());
        wrapper.in(ObjectUtils.isNotEmpty(authStr.getConsNo()),"xog.cons_no",authStr.getConsNo());
        if("0".equals(workOrderMonitorDTO.getFlag())){
            wrapper.eq("month(xog.dispatch_time)",LocalDate.now().getMonth().getValue());
        }
        if("1".equals(workOrderMonitorDTO.getFlag())){
            wrapper.eq("CONVERT(xog.dispatch_time,date)",LocalDate.now());
        }
        wrapper.orderByDesc("xog.dispatch_time");
        //开启分页功能
        PageMethod.startPage(Integer.parseInt(String.valueOf(page.getCurrent())), Integer.parseInt(String.valueOf(page.getSize())));
        return new PageInfo<>(baseMapper.findWorkOrderMonitors(wrapper));
    }

    /**
     * 查询预警工单列表无分页
     *
     * @param ids 批量id
     * @return List<WorkOrderMonitorVO> 返回预警工单列表
     */
    @Override
    public List<WorkOrderMonitorVO> selectWorkOrderMonitors(String ... ids) {
        QueryWrapper<WorkOrderMonitorVO> queryWrapper = new QueryWrapper<>();
        AuthInfoVo authStr = iUserAuthService.getAuthStr();
        queryWrapper.eq(StringUtils.isNotEmpty(authStr.getOrgNo()),"xog.org_no",authStr.getOrgNo());
        queryWrapper.in(ObjectUtils.isNotEmpty(authStr.getConsNo()),"xog.cons_no",authStr.getConsNo());
        queryWrapper.in("xog.id", Arrays.asList(ids));
        return baseMapper.findWorkOrderMonitors(queryWrapper);
    }

    /**
     * 查询工单监控无分页
     *
     * @param workOrderMonitorDTO 工单监控DTO类
     * @return List<WorkOrderMonitorVO> 返回工单监控列表
     */
    @Override
    public List<WorkOrderMonitorVO> selectWorkOrderMonitors(WorkOrderMonitorDTO workOrderMonitorDTO) {
        QueryWrapper<WorkOrderMonitorVO> queryWrapper = new QueryWrapper<>();
        AuthInfoVo authStr = iUserAuthService.getAuthStr();
        queryWrapper.eq(StringUtils.isNotEmpty(authStr.getOrgNo()),"xog.org_no",authStr.getOrgNo());
        queryWrapper.in(ObjectUtils.isNotEmpty(authStr.getConsNo()),"xog.cons_no",authStr.getConsNo());
        return baseMapper.findWorkOrderMonitors(queryWrapper);
    }

    /**
     * 工单预警按照各个类型汇总待办工单
     *
     * @param workOrderEarlyWarningDTO
     * @return List<WorkOrderPoolSummaryVO> 返回汇总数据
     */
    @Override
    public List<WorkOrderPoolSummaryVO> getXjOrderGeneralByStatus(WorkOrderEarlyWarningDTO workOrderEarlyWarningDTO) {
        QueryWrapper<WorkOrderPoolSummaryVO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("xog.status",ElectricPowerEnums.ORDER_STATUS_PROCESS.getValue());
        AuthInfoVo authStr = iUserAuthService.getAuthStr();
        queryWrapper.eq(StringUtils.isNotEmpty(authStr.getOrgNo()),"xog.org_no",authStr.getOrgNo());
//        queryWrapper.in(ObjectUtils.isNotEmpty(authStr.getConsNo()),"xog.cons_no",authStr.getConsNo());
//        queryWrapper.eq("xog.org_no",654010711);
        queryWrapper.in(ObjectUtils.isNotEmpty(authStr.getConsNo()),"xog.cons_no",authStr.getConsNo());
        queryWrapper.isNotNull("xog.type");
        queryWrapper.groupBy("xog.type");
        queryWrapper.orderByDesc("num");
        return baseMapper.selectXjOrderGeneralByStatus(queryWrapper);
    }
    @Autowired
    private XjOrderSourceMapper xjOrderSourceMapper;
    @Override
    public List<SystemOrdersVO> countSystemOrders(String status) {

        QueryWrapper<SystemOrdersVO> warpper = new QueryWrapper<SystemOrdersVO>();
        warpper.eq("xog.status",ElectricPowerEnums.ORDER_STATUS_PROCESS.getValue());
        warpper.isNotNull("xog.type");
        AuthInfoVo authStr = iUserAuthService.getAuthStr();
        warpper.eq(StringUtils.isNotEmpty(authStr.getOrgNo()),"xog.org_no",authStr.getOrgNo());
//        warpper.eq("xog.org_no",654010711);
        if (status != null) {
            warpper.eq("xog.status" ,status);
        }
        warpper.eq(StringUtils.isNotEmpty(authStr.getConsNo()),"xog.cons_no",authStr.getConsNo());
        warpper.groupBy("xoc.source_id");
        List<SystemOrdersVO> systemOrders = baseMapper.countSystemOrder(warpper);
       List<SystemOrdersVO> systemOrdersList =  xjOrderSourceMapper.selectSourceName();
        for (SystemOrdersVO systemOrdersVO : systemOrdersList) {
            systemOrdersVO.setOrderNum(0L);
            for (SystemOrdersVO vo : systemOrders) {
                if (systemOrdersVO.getId().equals(vo.getId())) {
                    systemOrdersVO.setOrderNum(vo.getOrderNum());
                }
            }
        }
        if (CollectionUtils.isNotEmpty(systemOrdersList)) {
            //AtomicReference<Long> orderNum = new AtomicReference<>(0L);
            systemOrdersList.forEach(systemOrdersVO -> {
                if (systemOrdersVO.getOrderNum() > 0) {
                    //orderNum.updateAndGet(v -> v + systemOrdersVO.getOrderNum());
                    QueryWrapper<XjOrderGeneralVO> queryWrapper = new QueryWrapper<XjOrderGeneralVO>();
                    queryWrapper.eq("xog.status",ElectricPowerEnums.ORDER_STATUS_PROCESS.getValue());
                    queryWrapper.eq("xos.id", systemOrdersVO.getId());
                    queryWrapper.eq(StringUtils.isNotEmpty(authStr.getOrgNo()),"xog.org_no",authStr.getOrgNo());
                    queryWrapper.eq(StringUtils.isNotEmpty(authStr.getConsNo()),"xog.cons_no",authStr.getConsNo());
                    queryWrapper.isNotNull("xog.type");
                    queryWrapper.groupBy("xog.type");
                    queryWrapper.orderByDesc("num");
                    //查询该系统下的工单类型统计
                    List<OrderTypeStatisticsVO> orderTypeStatisticsVOS = baseMapper.countOrderTypeBySystem(queryWrapper);
                    systemOrdersVO.setList(orderTypeStatisticsVOS);
                }
            });
            //AtomicReference<Map<String, Long>> collect = new AtomicReference<>();
            //systemOrders.forEach(
            //        item -> {
            //    //相同类型求和
            //    collect.set(item.getList().stream().collect(
            //            Collectors.toMap(
            //                    OrderTypeStatisticsVO::getType,
            //                    OrderTypeStatisticsVO::getNum,
            //                    Long::sum
            //            )
            //    ));
            //});
            //systemOrders.stream().collect(Collectors.toList())
            //List<OrderTypeStatisticsVO> list = new ArrayList<OrderTypeStatisticsVO>();
            //list.forEach(e -> {
            //    collect.get().forEach((k, v) -> {
            //        OrderTypeStatisticsVO orderTypeStatisticsVO = OrderTypeStatisticsVO.builder().type(k).num(v).build();
            //        list.add(orderTypeStatisticsVO);
            //    });
            //});
            //SystemOrdersVO systemOrderVO = SystemOrdersVO.builder().id("0").systemName("全部").orderNum(orderNum.get()).list(list).build();
            //systemOrders.add(systemOrderVO);
            return systemOrdersList;
        }
        return systemOrdersList;
    }

}
